package com.example.demo.config.login;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import lombok.extern.slf4j.Slf4j;

/**
 * 登陆失败时的处理
 * 
 * @author Administrator
 *
 */
@Slf4j
public class CustomFailureHandler implements AuthenticationFailureHandler {

	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException e) throws IOException, ServletException {

		// 这里也可以用String jsonString = JSONObject.toJSONString(b);
		// 进行返回指定格式对象response.getWriter().write(jsonString);

		log.info("请求路径:" + request.getRequestURL() + "" + response.getStatus());
		log.info("登陆错误:" + e);
		response.setContentType("application/json;charset=UTF-8");
		if (e instanceof UsernameNotFoundException) {
			response.getWriter().write("{\"msg\":\"登陆失败:用户不存在\"}");
		}
		if (e instanceof DisabledException) {
			response.getWriter().write("{\"msg\":\"登陆失败:用户被禁用\"}");
		}
		if (e instanceof BadCredentialsException) {
			response.getWriter().write("{\"msg\":\"登陆失败:用户名或密码错误\"}");
		}
		if (e instanceof LockedException) {
			response.getWriter().write("{\"msg\":\"登陆失败:账户锁定\"}");
		}
		if (e instanceof AccountExpiredException) {
			response.getWriter().write("{\"msg\":\"登陆失败:账户过期\"}");
		}
		if (e instanceof CredentialsExpiredException) {
			response.getWriter().write("{\"msg\":\"登陆失败:证书过期\"}");
		}
	}
}
